using System;
using System.Linq;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;

namespace HappyBa.Core.TasksModification
{
    class TasksManager : ITasksManager
    {
        private readonly ITargetProccessFacade facade;
        private readonly IDataCache cache;
        private readonly Connection connection;

        public TasksManager(ITargetProccessFacade facade, IDataCache cache, Config config)
        {
            this.facade = facade;
            this.cache = cache;
            this.connection = config.Settings.Connection;
        }

        public void AssignBa(string type, string id, string email)
        {
            Assign(type, id, email, "BA");
        }

        public void AssignDev(string type, string id, string email)
        {
            Assign(type, id, email, "Developer");
        }

        public void AssignQa(string type, string id, string email)
        {
            Assign(type, id, email, "QA");
        }

        public void AssignJob(string type, string id, string jobCode)
        {
            throw new System.NotImplementedException();
        }

        public void AssignJobMore(string type, string id, string jobCode)
        {
            throw new System.NotImplementedException();
        }

        public void ReName(string type, string id, string name)
        {
            throw new System.NotImplementedException();
        }

        private void Assign(string type, string id, string email, string role)
        {
            var model = new Assignment
            {
                Assignable = new Assignment { Id = int.Parse(id) },
                GeneralUser =
                    new User
                    {
                        Id =
                            cache.Metrics.Users.Single(x => string.Equals(x.Email, email, StringComparison.OrdinalIgnoreCase))
                                .Id
                    },
                Role = new Role { Name = role }
            };
            facade.CreateOrUpdate(connection, type, model);
        }

        private EntityBase BuildModel(string type, string id)
        {
            switch (type.ToLower())
            {
                case "userstory": return new UserStory {Id = int.Parse(id)};
                case "task": return new Task {Id = int.Parse(id)};
                case "project": return new Data.Project {Id = int.Parse(id)};
                default:
                    throw new ArgumentException("Unknown type:" + type);
            }
        }
    }
}